import { onMounted, onUnmounted, ref } from "vue";
// 第三方库 节流方法
import { throttle } from "underscore";
// 下拉到页面底部进行加载数据
export default function useScroll(elRef) {
    // 默认监听window对象
    let el = window
    const isReachBottom = ref(false)
    const clientHeight = ref(0)
    const scrollTop = ref(0)
    const scrollHeight = ref(0)
    // 判断逻辑
    const scrollListenerHandle = throttle(() => {
        if (el == window) {
            clientHeight.value = document.documentElement.clientHeight;
            scrollTop.value = document.documentElement.scrollTop;
            scrollHeight.value = document.documentElement.scrollHeight;
        } else {
            clientHeight.value = el.clientHeight;
            scrollTop.value = el.scrollTop;
            scrollHeight.value = el.scrollHeight;
        }
        // 当前页面距离顶部的距离加上窗口大小 等于页面总高度时候（滚动到底部） 加载更多数据
        if (clientHeight.value + scrollTop.value >= scrollHeight.value) {
            isReachBottom.value = true;
            console.log("到达底部");
        }
    }, 100)
    // 挂载
    onMounted(() => {
        // 如果有传值进来 监听该对象
        if (elRef) {
            el = elRef.value
        }
        el.addEventListener("scroll", scrollListenerHandle);
    });
    onUnmounted(() => {
        el.removeEventListener("scroll", scrollListenerHandle);
    });

    return { isReachBottom, clientHeight, scrollHeight, scrollTop }

}